﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UacHelper;

namespace MebApp.Launcher.Helpers
{
    public class RegEdit
    {
        public static void RegProtocol(string protocol, string startupFile)
        {
            var rootNames = Microsoft.Win32.Registry.ClassesRoot.GetSubKeyNames();
            if (!rootNames.Contains(protocol))
            {
                UacUtil.RunAsAdministrator();
                var surekamKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(protocol);
                var subKeyNames = surekamKey.GetSubKeyNames();
                var defaultIcon = surekamKey.CreateSubKey("DefaultIcon");
                defaultIcon.SetValue("", Path.GetFileNameWithoutExtension(startupFile));
                var shellKey = surekamKey.CreateSubKey("shell");
                var openKey = shellKey.CreateSubKey("open");
                var commandKey = openKey.CreateSubKey("command");
                surekamKey.SetValue("URL Protocol", "");
                commandKey.SetValue("", "\"" + startupFile + "\"" + " \"%1\"");
            }
            else
            {
                //如果应用位置变更，则删除重建
                var value = "\"" + startupFile + "\"" + " \"%1\"";
                var surekamKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(protocol);
                var regValue = surekamKey.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue("").ToString();
                if (regValue != value)
                {
                    UacUtil.RunAsAdministrator();
                    UnregProtocol(protocol);
                    RegProtocol(protocol, startupFile);
                }
            }
        }

        public static void UnregProtocol(string protocol)
        {
            try
            {
                Microsoft.Win32.Registry.ClassesRoot.DeleteSubKeyTree(protocol);
            }
            catch { }
        }
    }
}
